package com.yunqiao.common.utils;

import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yunqiao.common.exception.CustomApiException;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class MapToolsUtils {
    private static final String KEY = "c6eb7efabc60b0f2f6f077b0a457956f";
    /**
     * 根据经纬度获取距离
     * @param form
     * @param to
     * @return
     */
    public static Long getDistance(String form, String to) {
        Dict dict = Dict.create()
                .set("origins", form) //from=39.071510,117.190091 起点坐标
                .set("destination", to)  // 可以多个 to=39.071510,117.190091;40.007632,116.389160;39.840177,116.463318
                .set("output", "JSON") //返回格式：支持JSON/Jhttps://restapi.amap.com/v3/direction/walkingSONP，默认JSON
                .set("key", KEY);
        String jsonStr = HttpUtil.get("https://restapi.amap.com/v3/distance", dict);
        JSONObject json = JSON.parseObject(jsonStr);
        Long distance=0l;
        if(json.getInteger("status")==1){
            JSONArray array = json.getJSONArray("results");
            for (int i = 0; i < array.size(); i++) {
                JSONObject obj = array.getJSONObject(i);
                distance=obj.getLong("distance");
                break;
            }
            return distance;
        }
        throw new CustomApiException("");
    }
    /**
     * 根据地址获取经纬度
     * @param address 地址
     * @return
     */
    public static String getLocation(String address) {
        Dict dict = Dict.create()
            .set("address", address)// ：详细地址
            .set("output", "JSON") //返回格式：支持JSON/JSONP，默认JSON
            .set("key", KEY);

        String jsonStr = null;
        Map map = null;
        do {
            try {
                jsonStr = HttpUtil.get("https://restapi.amap.com/v3/geocode/geo", dict);
                Console.log(jsonStr);
                map = JSONUtil.toBean(jsonStr, Map.class);
                Console.log(map);
            } catch (Exception e) {
                log.error("获取经纬度出现错误", e);
            }
        } while (MapUtil.getInt(map, "status") != 1);
        List<Map<String, Object>> geocodes = MapUtil.get(map, "geocodes", List.class);
        return geocodes.get(0).get("location").toString();
    }

    /**
     * 根据金纬度获取市
     * @param location 经纬度
     * @return
     */
    public static String getAddress(String location) {
        Dict dict = Dict.create()
            .set("location", location)// ：详细地址
            .set("output", "JSON") //返回格式：支持JSON/JSONP，默认JSON
            .set("key", KEY);
        String jsonStr = null;
        Map map = null;
        do {
            try {
                jsonStr = HttpUtil.get("https://restapi.amap.com/v3/geocode/regeo", dict);
                Console.log(jsonStr);
                map = JSONUtil.toBean(jsonStr, Map.class);
                Console.log(map);
            } catch (Exception e) {
                log.error("获取地址出现错误", e);
            }
        } while (MapUtil.getInt(map, "status") != 1);
        Map<String, Object> geocodes = MapUtil.get(map, "regeocode", Map.class);
        Map<String, Object> addressComponent = MapUtil.get(geocodes, "addressComponent", Map.class);
        String city = MapUtil.getStr(addressComponent, "city");
        if (city.equals("[]")) {
            city = MapUtil.getStr(addressComponent, "province");
        }
        return city;

    }
    /**
     * 根据金纬度获取市
     * @param location 经纬度
     * @return
     */
    public static Map getAddressMap(String location) {
        Dict dict = Dict.create()
                .set("location", location)// ：详细地址
                .set("output", "JSON") //返回格式：支持JSON/JSONP，默认JSON
                .set("key", KEY);

        String jsonStr = null;
        Map map = null;
        do {
            try {
                jsonStr = HttpUtil.get("https://restapi.amap.com/v3/geocode/regeo", dict);
                Console.log(jsonStr);
                map = JSONUtil.toBean(jsonStr, Map.class);
                Console.log(map);
            } catch (Exception e) {
                log.error("获取地址出现错误", e);
            }
        } while (MapUtil.getInt(map, "status") != 1);
        Map<String, Object> geocodes = MapUtil.get(map, "regeocode", Map.class);
        Map<String, Object> addressComponent = MapUtil.get(geocodes, "addressComponent", Map.class);
        String city = MapUtil.getStr(addressComponent, "city");
        if (city.equals("[]")) {
            city = MapUtil.getStr(addressComponent, "province");
        }
        return addressComponent;

    }

    /**
     * 根据经纬度 获得详细地址
     * @param location
     * @return
     */
    public static Map<String, Object> getAddressFormatted(String location){
        Dict dict = Dict.create()
                .set("location", location)// ：详细地址
                .set("output", "JSON") //返回格式：支持JSON/JSONP，默认JSON
                .set("roadlevel",1)
                .set("extensions","all")
                .set("key", KEY);

        String jsonStr = null;
        Map map = null;
        do {
            try {
                jsonStr = HttpUtil.get("https://restapi.amap.com/v3/geocode/regeo", dict);
                Console.log(jsonStr);
                map = JSONUtil.toBean(jsonStr, Map.class);
                Console.log(map);
            } catch (Exception e) {
                log.error("获取地址出现错误", e);
            }
        } while (MapUtil.getInt(map, "status") != 1);
        Map<String, Object> geocodes = MapUtil.get(map, "regeocode", Map.class);
        Map<String, Object> param= new HashMap<>();
        JSONObject json= JSONObject.parseObject(JSON.toJSONString(geocodes.get("addressComponent")));
        JSONArray json1= JSON.parseArray(JSON.toJSONString(geocodes.get("aois")));
        String formatted_address= (String) geocodes.get("formatted_address");
        String province=json.getString("province");
        String city=json.getString("city");
        String district=json.getString("district");
        String township=json.getString("township");
        System.out.println(formatted_address);
        System.out.println(province+"  "+city+" "+district+" "+township+" ");
        if(city.equals("[]")){
            city="";
        }
        if(district.equals("[]")){
            district="";
        }
        if(township.equals("[]")){
            township="";
        }
        param.put("address",formatted_address);
        JSONObject obj=new JSONObject();
        obj.put("name",formatted_address.replace(province,"").replace(city,"").replace(district,"").replace(township,""));
        param.put("building",obj);
/*        if(json1.size()>0){
            param.put("building",json1.get(0));
            param.put("address",json.getString("province")+json.getString("city")+json.getString("district")+json.getString("township"));
        }else{
            param.put("address",geocodes.get("formatted_address"));
        }
        if(!json.getJSONObject("building").getString("name").equals("[]")){
            param.put("building",json.getJSONObject("building"));
            param.put("address",json.getString("province")+json.getString("city")+json.getString("district")+json.getString("township"));
        }*/

        return param;
    }

    public static Long getTime(String form, String to) {
        Dict dict = Dict.create()
            .set("origin", form) //from=39.071510,117.190091 起点坐标
            .set("destination", to)  // 可以多个 to=39.071510,117.190091;40.007632,116.389160;39.840177,116.463318
            .set("output", "JSON") //返回格式：支持JSON/Jhttps://restapi.amap.com/v3/direction/walkingSONP，默认JSON
            .set("key", KEY);
        String jsonStr = HttpUtil.get("https://restapi.amap.com/v3/direction/driving", dict);
        Console.log(jsonStr);
        Map map = JSONUtil.toBean(jsonStr, Map.class);
        if (MapUtil.getInt(map, "status") == 1) {
            map = MapUtil.get(map, "route", Map.class);
            List<Map<String, Object>> list = MapUtil.get(map, "paths", List.class);
            map = list.get(0);
            Long distance = MapUtil.getLong(map, "duration");
            return distance;
        }
        throw new CustomApiException("获取所需时间出现错误");
    }
    public static Map<String,Object> getDistances(String start,String to){
        Dict dict = Dict.create()
                .set("origins", start) //from=39.071510,117.190091 起点坐标
                .set("destination", to)  // 可以多个 to=39.071510,117.190091;40.007632,116.389160;39.840177,116.463318
                .set("output", "JSON") //返回格式：支持JSON/Jhttps://restapi.amap.com/v3/direction/walkingSONP，默认JSON
                .set("key", KEY);
        String jsonStr = HttpUtil.get("https://restapi.amap.com/v3/distance", dict);
        JSONObject json = JSON.parseObject(jsonStr);
        Integer d=0;
        Integer time=0;
        if(json.getInteger("status")==1){
            JSONArray array = json.getJSONArray("results");
            for (int i = 0; i < array.size(); i++) {
                JSONObject obj = array.getJSONObject(i);
                d=obj.getInteger("distance");
                time=obj.getInteger("duration");
                break;
            }
        }
        Map<String,Object> map=new HashMap<>();
        map.put("distance",d);
        map.put("duration",time);
        return map;
    }
    public static void main(String[] args) {
        //String aa = getLocation("北京");
        //        Long distance = getTime("116.481028,39.989643", "116.434446,39.90816");
        //        System.out.println(distance);
        //Console.log(getLocation("北京东城"));
        //Console.log(getAddress("120.155070,30.274084"));

        Map map = getAddressMap("106.55073,29.56471");
        System.out.println(map);
    }
}
